<template>
  <div class="container list" v-loading="loading">
    <div class="handle-box">
      <el-button type="primary" :icon="Plus" @click="add">新增</el-button>
    </div>

    <el-row>
      <el-table :data="items" :row-key="(row) => row.id" table-layout="auto">
        <el-table-column label="标签" width="120">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-tag v-for="(tag, id) in scope.row.tags" :key="tag">{{
                tag
              }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column sortable prop="date" label="更新时间" width="120" />
        <el-table-column
          :filters="filters"
          :filter-method="filterTag"
          prop="name"
          label="项目名称"
          width="120"
        />
        <!-- <el-table-column prop="desciption" label="简述" width="180" /> -->
        <el-table-column prop="detail" label="详情" min-width="240" />
        <el-table-column prop="url" label="原文" min-width="100" />
        <el-table-column prop="author" label="原作者" />
        <el-table-column prop="contributor" label="贡献者" />

        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" type="primary" @click="edit(scope.row)"
              >编辑</el-button
            >
            <el-popconfirm
              title="确定要删除当前记录吗?"
              @confirm="remove(scope.row)"
              :width="200"
            >
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-if="total > 0"
          background
          layout="total, prev, pager, next"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          @current-change="fetchData()"
        />
      </div>
    </el-row>

    <el-dialog
      v-model="showDialog"
      :title="title"
      :close-on-click-modal="false"
      style="width: 90%; max-width: 1000px"
    >
      <el-form :model="item" label-width="120px" ref="formRef" :rules="rules">
        <el-form-item label="标签：" prop="tags">
          <el-select
            v-model="item.tags"
            placeholder="请选择标签"
            allow-create
            filterable
            multiple 
          >
            <el-option
              v-for="item in tags"
              :value="item"
              :label="item"
              :key="item"
              >{{ item }}
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="更新时间：" prop="name">
          <el-date-picker
            v-model="item.date"
            type="date"
            placeholder="Pick a day"
            size="default"
            value-format="YYYY-MM-DD"
            :default-value="item.date"
          />
        </el-form-item>

        <el-form-item label="项目名称：" prop="value">
          <el-input v-model="item.name" autocomplete="off" />
        </el-form-item>
         <el-form-item label="详情：" prop="value">
          <el-input v-model="item.detail" autocomplete="off" />
        </el-form-item>

        <el-form-item label="原文：" prop="value">
          <el-input v-model="item.url" autocomplete="off" />
        </el-form-item>

        <el-form-item label="原作者：" prop="value">
          <el-input v-model="item.author" autocomplete="off" />
        </el-form-item>

        <el-form-item label="贡献者：" prop="value">
          <el-input v-model="item.contributor" autocomplete="off" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="save">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import { httpGet, httpPost } from "@/utils/http";
import { ElMessage } from "element-plus";
import { dateFormat, removeArrayItem } from "@/utils/libs";
import { Sortable } from "sortablejs";

// 变量定义
const items = ref([]);
const tags = ref([]);
const item = ref({});
const showDialog = ref(false);
const title = ref("");
const currentPage = ref(1);
const pageSize = ref(15);
const total = ref(1000);

const loading = ref(true);
const formRef = ref(null);

// 获取数据
const fetchData = () => {
  httpGet(
    `/api/ai/info/get?pageNum=${currentPage.value}&pageSize=${pageSize.value}`
  )
    .then((res) => {
      console.log(res);
      items.value = res.data;
      loading.value = false;
    })
    .catch(() => {
      ElMessage.error("获取数据失败");
    });
};

const fetchTags = () => {
  httpGet(
    '/api/ai/tags/get'
  )
    .then((res) => {
      tags.value = res.data;
    })
    .catch(() => {
      ElMessage.error("获取tags失败");
    });
};

const updateValue = (params) => {
  httpPost(
    '/api/ai/info/update', params
  )
    .then((res) => {
      ElMessage.success("更新成功");
    })
    .catch(() => {
      ElMessage.error("更新失败");
    });
};

onMounted(() => {
  fetchData();
  fetchTags();
});

const add = function () {
  title.value = "新增资讯";
  showDialog.value = true;
};

const edit = function (row) {
  title.value = "修改资讯";
  showDialog.value = true;
  item.value = row;
};

const save = function () {
  formRef.value.validate((valid) => {
    if (valid) {
      showDialog.value = false;
      httpPost("/api/ai/info/create", item.value)
        .then((res) => {
          ElMessage.success("操作成功！");
          fetchData()
        }) 
        .catch((e) => {
          ElMessage.error("操作失败，" + e.message);
        });
    } else {
      return false;
    }
  });
};

const remove = function (row) {
  httpGet("/api/ai/info/remove?id=" + row.id)
    .then(() => {
      ElMessage.success("删除成功！");
      items.value = removeArrayItem(items.value, row, (v1, v2) => {
        return v1.id === v2.id;
      });
    })
    .catch((e) => {
      ElMessage.error("删除失败：" + e.message);
    });
};
</script>

<style lang="stylus" scoped>
@import '@/assets/css/admin/form.styl';

.list {
  .opt-box {
    padding-bottom: 10px;
    display: flex;
    justify-content: flex-end;

    .el-icon {
      margin-right: 5px;
    }
  }

  .el-select {
    width: 100%;
  }
}
</style>